<template>
    <div class="yCamera">
        <el-dialog title="拍照" fullscreen  :visible.sync="option.isShow"  v-dialogDrag :append-to-body="true" :close-on-click-modal='false'  :before-close="beforeClose">
            <div class="box">
                <div>
                    <video :id="videoId" :ref="videoId" autoplay="autoplay" :width="width" :height="height" class="video" v-if="option.type=='camera'">当前浏览器不支持video</video>
                    <div v-else class="fileName">
                        <input type="file" @change="chooseImg($event)" class="fileBtn">
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                    <div class="canvasBox" ><canvas v-if='option.isShow' :class="{canDraw: 'canvas'}" :id="canvasId" :ref="canvasId" :width="width" :height="height"  @mousedown="canvasDown($event)" @mouseup="canvasUp($event)" @mousemove="canvasMove($event)"></canvas></div>
                </div>
                <div slot="footer" class="dialog-footer text-center">
                    <el-button @click="openMedia" v-if="option.type=='camera'">开启摄像头</el-button>
                    <el-button @click="closeMedia" v-if="option.type=='camera'">关闭摄像头</el-button>
                    <el-button @click="takePhoto" v-if="option.type=='camera'">拍照</el-button>
                    <el-button @click="tag">添加标记</el-button>
                    <el-button @click="clearTag">清除标记</el-button>
                    <el-button type="primary" @click="confirm">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import baseHttp from '@/axios/baseHttp.js';
    export default {
        name:'yCamera',
        props: {
            option:Object,
            action:String,
            itemId:Number,
        },
        data(){
            return {
                hasCamera:false,/**是否有摄像头 */
                videoId:'video'+new Date().getTime(),
                canvasId:'canvasId'+new Date().getTime(),
                width:360,
                height:360,
                 // 是否处于绘制状态
                canvasMoveUse: false,
                canDraw:false,
                mediaStreamTrack:null,
                 // canvas对象
                context: {},
                img:null,
                imageUrl:'',
                imgFormat: ['jpg', 'png'] // 图片上传格式
            }
        },
        created(){
        },
        methods:{
            openMedia(){
                let self=this;
                if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
                    self.hasCamera=true;
                    navigator.mediaDevices.getUserMedia({ audio: true, video: {width: self.width, height: self.height}}).then(function(mediaStream){
                        self.mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
                        self.$refs[self.videoId].srcObject = mediaStream;
                        self.$refs[self.videoId].play();
                    }).catch(function(err) {
                        self.hasCamera=false;
                        self.$message.error('未找到摄像头！')
                    })
                }
            },
            takePhoto(){
                let self=this;
                   //获得Canvas对象
                self.context = self.$refs[self.canvasId].getContext('2d');
                self.context.strokeStyle='red'
                self.context.beginPath();
                self.context.drawImage(self.$refs[self.videoId], 0, 0, self.width, self.height);
                // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
               self.img = self.$refs[self.canvasId].toDataURL();

            },
            tag(){/**添加标记 */
                this.canDraw=true;
            },
            clearTag(){/**清除标记 */
                let self = this;
                self.context=null;
                var a= self.$refs[self.canvasId].getContext('2d');
                a.clearRect(0,0,self.width,self.height);
                a.beginPath();
                a.strokeStyle='red'
                let img = new Image();
                img.src=self.img;
                img.onload=()=>{
                    var imgObj= self.imgRoate(img.width,img.height);
                    a.drawImage(img, imgObj.centerX, imgObj.centerY, imgObj.imgWidth,imgObj.imgHeight );
                    self.context=a;
                }

            },
            canvasDown(e){
                let self = this;
                if(self.canDraw){
                    self.context.moveTo(e.clientX-self.$refs[self.canvasId].offsetLeft,e.clientY-self.$refs[self.canvasId].offsetTop);
                    self.canvasMoveUse = true;
                }

            },
            canvasMove(e){
                let self = this;
                if(self.canDraw&&self.canvasMoveUse){
                    self.context.lineTo(e.clientX-self.$refs[self.canvasId].offsetLeft,e.clientY-self.$refs[self.canvasId].offsetTop);
                    self.context.stroke();
                }
            },
            canvasUp(e){
                let self = this;
                 self.canvasMoveUse = false;
            },
            closeMedia(){
                this.mediaStreamTrack.stop();
            },
            confirm(){
                let self = this;
                if(self.hasCamera || self.option.type!='camera'){
                    self.option.type=='camera' ? self.closeMedia():'';
                    let path = self.$refs[self.canvasId].toDataURL('image/png');
                    self.uploadSectionFile(path,function(){
                        self.$emit('uploadSuccess',{imageUrl:self.imageUrl,isShow:false,itemId:self.itemId});
                    });
                }else{
                    self.option.type=='camera' ? self.closeMedia():'';
                    self.$emit('uploadSuccess',{imageUrl:'',isShow:false,itemId:self.itemId});
                }
            },
            uploadSectionFile(imgurl,cb){
                let self = this;
                let form =new FormData();
                let  file=self.dataURLtoFile(imgurl);
                form.append('file',file);
                let loading =self.$loading({
                    lock: true,
                    text: '图片上传中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                    });
                baseHttp.uploadImg(self.action,form).then(res=>{
                    self.imageUrl=res;
                    loading.close();
                    self.$message.success('图片上传成功')
                    cb()
                },error=>{
                    self.$message.error('图片上传失败');
                     loading.close();
                })
            },
              // 将base64转换成file对象
            dataURLtoFile (dataurl, filename = 'file') {
                let arr = dataurl.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let suffix = mime.split('/')[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], `${filename}.${suffix}`, {type: mime})
            },
            beforeClose(){
                 this.$emit('closeDialog')
            },
            chooseImg(e){
                let self = this;
                if(e.target.files.length!==0){
                    let file=e.target.files[0];
                    let arr =self.imgFormat
                    let str = file.name.split('.').pop();
                    if(arr.indexOf(str) >-1){
                    self.changeDataURL(file, (dataUrl) => {
                        self.img = dataUrl;
                        var a= self.$refs[self.canvasId].getContext('2d');
                        a.clearRect(0,0,self.width,self.height);
                        a.beginPath();
                        a.strokeStyle='red'
                        let img = new Image();
                        img.src=dataUrl;
                        img.onload=()=>{
                            var imgObj= self.imgRoate(img.width,img.height);
                            a.drawImage(img, imgObj.centerX, imgObj.centerY, imgObj.imgWidth,imgObj.imgHeight );
                            self.context=a;
                        }
                    })
                    }else{
                        self.$message.error("图片格式错误")
                    }
                }
            },
            imgRoate(width,height){
                let self = this;
                let imgWidth,imgHeight,opt,centerX,centerY;
                if(width>height){
                    opt= self.width/width;
                    imgWidth=self.width;
                    imgHeight=height*opt
                    centerX=0;
                    centerY=(self.height-imgHeight)/2
                }else{
                    opt= self.height/height;
                    imgHeight=self.height;
                    imgWidth=self.width*opt;
                    centerY=0;
                    centerX=(self.width-imgWidth)/2
                }
                return {
                    imgWidth,
                    imgHeight,
                    centerX,
                    centerY
                }
            },
            handleChange(file, fileList){
               let self=this;
               self.changeDataURL(file, (dataUrl) => {

			  })
            },
            // 转换成dataUrl
            changeDataURL:function (fileObj, callback) {
                let file = new FileReader()
                file.readAsDataURL(fileObj)
                file.onload = (e) => { callback(e.target.result)}
            }
        }
    }
</script>
<style scoped>
.box{
    display: block;
    margin:auto;
    width:760px;
    overflow: hidden;
}
.video{
    background: #999;
    display: block;
    float: left;

}
.text-center{
    text-align: center;
}
.canvasBox{
    display: block;
    float: left;
    width: 360px;
    height: 360px;
    margin-left:24px;
}
.canvas{
    display: block;
    cursor: crosshair;
    border:1px solid #aaa;
    overflow: hidden;
}
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .fileName{
    float: left;
    width: 360px;
    height: 360px;
    border:1px dashed #aaa;
    position: relative;
    box-sizing: border-box;
  }
    .fileName .fileBtn{
        position: absolute;
        top:0;
        left:0;
        display: block;width: 100%;
        height:100%;
        opacity: 0;
    }
    .fileName:hover{
        border-color: #409EFF;
    }
   .fileName .avatar-uploader-icon{
       font-size: 28px;
        color: #8c939d;
        width: 360px;
        height: 360px;
        line-height:360px;
        text-align: center;
  }
  .dialog-footer{
      clear: both;
     padding:24px 0;
  }
</style>

